/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.controller.travel.weixin;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.finalist.Message;
import com.finalist.OrderVo;
import com.finalist.controller.shop.BaseController;
import com.finalist.entity.Member;
import com.finalist.entity.Order;
import com.finalist.entity.OrderItem;
import com.finalist.entity.Product;
import com.finalist.entity.Review;
import com.finalist.entity.Sn;
import com.finalist.entity.Order.OrderStatus;
import com.finalist.entity.Order.PaymentStatus;
import com.finalist.service.MemberService;
import com.finalist.service.OrderItemService;
import com.finalist.service.OrderService;
import com.finalist.service.ProductService;
import com.finalist.service.ReviewService;
import com.finalist.service.SnService;
import com.finalist.util.DateUtil;

/**
 * Controller  订单
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
@Controller("travelWeixinOrderController")
@RequestMapping("/travel/weixin/order")
public class OrderController extends BaseController
{
	protected static final String VIEW = "/travel/weixin/order/";
	
	 @Resource(name = "productServiceImpl")
	 private ProductService productService;
	 @Resource(name = "memberServiceImpl")
	 private MemberService memberService;
	 @Resource(name = "orderServiceImpl")
	 private OrderService orderService;
	 @Resource(name = "orderItemServiceImpl")
	 private OrderItemService orderItemService;
	 
	 @Resource(name = "reviewServiceImpl")
	 private ReviewService reviewService;
	 
	 @Resource(name = "snServiceImpl")
	 private SnService snService;
	 
	 /**
     * 生成订单
     */
    @RequestMapping(value = "/createOrder", method = RequestMethod.GET)
    public String createOrder(Long productId, ModelMap model)
    {
    	Product product=productService.find(productId);
    	model.put("product", product);
    	if(product.getDefaultDateString()==null){
    		return ERROR_VIEW;
    	}
        return VIEW+"createOrder";
    }
    
    @RequestMapping(value = "/updateOrder", method = RequestMethod.GET)
    public String updateOrder(Long productId, Long orderId,ModelMap model)
    {
    	model.put("product", productService.find(productId));
    	model.put("order", orderService.find(orderId));
    	return VIEW+"createOrder";
    }
    
	@RequestMapping(value = "/deleteMember", method = RequestMethod.GET)
	public @ResponseBody
	OrderVo deleteMember(Long id){
		OrderItem item=orderItemService.find(id);
		OrderVo vo=new OrderVo();
		if(item!=null&&item.getOrder()!=null){
			Order order=orderService.find(item.getOrder().getId());
			if(order!=null){
				if(order.getTotalNum()==1){
					return null;
				}
				if(item.getIsAdult()){
					order.setAdultNum(order.getAdultNum()-1);
				}else{
					order.setChildrenNum(order.getChildrenNum()-1);
				}
				orderItemService.delete(item);
				List<OrderItem> items=new ArrayList<OrderItem>();
				if(order!=null&&order.getOrderItems()!=null&&order.getOrderItems().size()!=0){
					for(OrderItem item1:order.getOrderItems()){
						if(item1.getId()!=id){
							items.add(item1);
						}
					}
				}
				order.setOrderItems(items);
				orderService.update(order);
				vo.setAdultNum(order.getAdultNum());
				vo.setChildrenNum(order.getChildrenNum());
			}
		}
		return vo;
	}
    @RequestMapping(value = "/countPrice", method = RequestMethod.GET)
	public @ResponseBody
	BigDecimal countPrice(Long productId,Integer adultNum,Integer childrenNum,Boolean isShareHouse){
    	BigDecimal tempPrice=new BigDecimal(0);
    	if(productId==null||adultNum==null||childrenNum==null||isShareHouse==null){
    		return tempPrice;
    	}
    	Product product=productService.find(productId);
    	BigDecimal adultAmount=new BigDecimal(0);
    	BigDecimal childrenAmount=new BigDecimal(0);
    	if(isShareHouse){
    		adultAmount=product.getPrice().multiply(new BigDecimal(adultNum));
    		childrenAmount=product.getChildrenPrice().multiply(new BigDecimal(childrenNum));
    	}else{
    		adultAmount=(product.getPrice().add(product.getHoursePrice())).multiply(new BigDecimal(adultNum));
    		childrenAmount=(product.getChildrenPrice().add(product.getHoursePrice())).multiply(new BigDecimal(childrenNum));
    	}
		tempPrice=adultAmount.add(childrenAmount);
		return tempPrice;
	}
    
    @RequestMapping(value = "/toAddMember", method = RequestMethod.GET)
    public String toAddMember(Long productId,Long orderId,ModelMap model){
    	Product product= productService.find(productId);
    	Order oldOrder=orderService.find(orderId);
    	model.put("product", product);
    	model.put("order", oldOrder);
    	if(oldOrder!=null&&oldOrder.getAdultNum()==oldOrder.getTmepAdult()){
			model.put("isAdult",false);
			model.put("count", oldOrder.getChildrenNum()-oldOrder.getTmepChildren());
		}else if(oldOrder!=null&&oldOrder.getAdultNum()>oldOrder.getTmepAdult()){
			model.put("isAdult",true);
			model.put("count", oldOrder.getAdultNum()-oldOrder.getTmepAdult());
		}
    	return VIEW+"addMember";
    }
    
    @RequestMapping(value = "/toFirstAddMember", method = RequestMethod.GET)
    public String toFirstAddMember(Long productId,Long orderId,ModelMap model){
    	Product product= productService.find(productId);
    	Order oldOrder=orderService.find(orderId);
    	model.put("order", oldOrder);
		model.put("isAdult", true);
		model.put("product", product);
		model.put("count", oldOrder.getAdultNum());
    	return VIEW+"addMember";
    }
    
    @RequestMapping(value = "/addMember", method = RequestMethod.GET)
    public String saveOrUpdateOrder(Long productId , Order order,String startingDate,ModelMap model,HttpServletRequest request)
    {
    	try {
			Product product= productService.find(productId);
			model.put("product", product);
			if(order!=null&&order.getId()!=null){
				Order oldOrder=orderService.find(order.getId());
				Long totalCount=oldOrder.getAdultNum()+oldOrder.getChildrenNum();
				if(oldOrder.getOrderItems()!=null&&oldOrder.getOrderItems().size()==totalCount&&order.getTotalNum()<=totalCount){
					return "redirect:updateOrder.jhtml?productId="+productId+"&orderId="+oldOrder.getId();
				}
				List<OrderItem> orderItems=oldOrder.getOrderItems();
				if(order.getAdultNum()!=null){
					oldOrder.setAdultNum(order.getAdultNum());
				}
				if(order.getChildrenNum()!=null){
					oldOrder.setChildrenNum(order.getChildrenNum());
				}
				if(order.getIsShareHouse()!=null){
					oldOrder.setIsShareHouse(order.getIsShareHouse());
				}
				if(order.getPhoneName()!=null){
					oldOrder.setPhoneName(order.getPhoneName());
				}
				if(order.getPhone()!=null){
					oldOrder.setPhone(order.getPhone());
				}
				if(startingDate!=null){
					oldOrder.setGoDate(DateUtil.parseDate(startingDate));
				}
				if(order.getGender()!=null){
					oldOrder.setGender(order.getGender());
				}
				if(order.getEmail()!=null){
					oldOrder.setEmail(order.getEmail());
				}
				System.out.println(orderItems.size());
				for (Iterator<OrderItem> iterator = order.getOrderItems()
						.iterator(); iterator.hasNext();) {
					OrderItem orderItem=iterator.next();
					orderItem.setSn(snService.generate(Sn.Type.order));
					orderItem.setOrder(oldOrder);
					orderItem.setPrice(product.getPrice());
					orderItem.setQuantity(1);
					orderItem.setName(product.getName());
					orderItem.setFullName(product.getName());
					orderItem.setProduct(product);
					orderItems.add(orderItem);
				}
				oldOrder.setOrderItems(orderItems);
				orderService.update(oldOrder);
				/*model.put("order", oldOrder);*/
				
				System.out.println(oldOrder.getOrderItems().size());
				totalCount=oldOrder.getAdultNum()+oldOrder.getChildrenNum();
				
				if(oldOrder.getOrderItems()!=null&&oldOrder.getOrderItems().size()==totalCount){
					return "redirect:updateOrder.jhtml?productId="+productId+"&orderId="+oldOrder.getId();
				}
				return "redirect:toAddMember.jhtml?productId="+productId+"&orderId="+oldOrder.getId();
			}else{
				Member member = (Member)request.getAttribute("currentUser");
				if(member==null){
					member = memberService.findByUnionId("1");
				}
				order.setMember(member);
				order.setProductName(product.getName());
				
				if(product.getAdmin()!=null){
					order.setAdminId(product.getAdmin().getId());
				}
				
				if(startingDate!=null){
					order.setGoDate(DateUtil.parseDate(startingDate));
				}
				
				order.setSn(snService.generate(Sn.Type.order));
				order.setOrderStatus(OrderStatus.unconfirmed);
				order.setPaymentStatus(PaymentStatus.unpaid);
		    	order.setExpire(DateUtils.addMinutes(new Date(), 45));
				orderService.save(order);
				/*model.put("order", order);
				model.put("isAdult", true);
				model.put("count", order.getAdultNum());*/
				return "redirect:toFirstAddMember.jhtml?productId="+productId+"&orderId="+order.getId();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    }
    
    @RequestMapping(value = "/editMember", method = RequestMethod.GET)
    public String editMerber(Long orderItemId,ModelMap model){
    	model.put("orderItem", orderItemService.find(orderItemId));
    	return VIEW+"editMember";
    }
    
    @RequestMapping(value = "/updateMember", method = RequestMethod.GET)
    public String updateMember(OrderItem orderItem,ModelMap model){
    	OrderItem oldOrderItem=orderItemService.find(orderItem.getId());
    	oldOrderItem.setMemberName(orderItem.getMemberName());
    	oldOrderItem.setGender(orderItem.getGender());
    	orderItemService.update(oldOrderItem);
    	model.put("order", oldOrderItem.getOrder());
    	model.put("product", oldOrderItem.getProduct());
    	return VIEW+"createOrder";
    }
    
    @RequestMapping(value = "/buyNow", method = RequestMethod.GET)
    public String buyNow(Order order ,ModelMap model,String startingDate,Boolean isMyCenter){
    	if(order!=null&&order.getId()!=null){
    		Order oldOrder=orderService.find(order.getId());
    		if(oldOrder!=null&&oldOrder.getOrderItems()!=null&&oldOrder.getOrderItems().size()!=0){
    			Product product=oldOrder.getOrderItems().get(0).getProduct();
    			if(product.getDefaultDateString()==null){
    				return ERROR_VIEW;
    			}
    		}
    		
    		if(isMyCenter!=null&&isMyCenter){
        		model.put("order", oldOrder);
        		return VIEW+"orderConfirm";
        	}
    		oldOrder.setAdultNum(order.getAdultNum());
    		oldOrder.setChildrenNum(order.getChildrenNum());
    		oldOrder.setPhone(order.getPhone());
    		oldOrder.setEmail(order.getEmail());
    		oldOrder.setPhoneName(order.getPhoneName());
    		if(startingDate!=null){
    			oldOrder.setGoDate(DateUtil.parseDate(startingDate));
    		}
    		oldOrder.setGender(order.getGender());
    		oldOrder.setIsShareHouse(order.getIsShareHouse());
    		oldOrder.setPaymentStatus(PaymentStatus.unpaid);
    		oldOrder.setOrderStatus(OrderStatus.unconfirmed);
    		oldOrder.setExpire(DateUtils.addMinutes(new Date(), 45));
    		oldOrder.setIsEffective(true);
    		orderService.update(oldOrder);
    		model.put("order", oldOrder);
    		return VIEW+"orderConfirm";
    	}else{
    		return ERROR_VIEW;
    	}
    	
    }
    
    @RequestMapping("/changeStatus")
	@ResponseBody
    public Order cancellOrder(Long orderId,String status,HttpServletRequest request,ModelMap model){
    	Order order =  orderService.find(orderId);
    	if("cancle".equals(status)){
    		order.setOrderStatus(OrderStatus.cancelled);
    	}else if ("complete".equals(status)){
    		order.setOrderStatus(OrderStatus.completed);
    	}
    	orderService.update(order);
    	return order;
    }
    
    @RequestMapping(value = "/orderDetail")
    public String orderDeatil(Long orderId , ModelMap model){
    	Order order =orderService.find(orderId); 
    	model.put("order", order);
    	Date d = order.getGoDate();
    	SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
    	if(d!=null){
    		model.put("beginDate", format.format(d));
    	}
    	if(order.getOrderItems()!=null && order.getOrderItems().size()>0){
    		model.put("product", order.getOrderItems().get(0).getProduct());
    	}
    	return VIEW+"orderDetail";
    }
    
    @RequestMapping("/evaluation")
  	@ResponseBody
      public String evaluation(Review review,Long productId,HttpServletRequest request,ModelMap model){
    	try {
    		Member member = (Member)request.getAttribute("currentUser");
    		review.setMember(member);
    		Product product =productService.find(productId);
    		review.setProduct(product);
    		review.setIp("127.0.0.1");
    		review.setIsShow(true);
    		if(product!=null&&product.getAdmin()!=null){
    			review.setAdminId(product.getAdmin().getId());
    		}
    		reviewService.save(review);
		} catch (Exception e) {
			e.printStackTrace();
		}
      	return "";
      }
    
    
    @RequestMapping(value = "/testCalendar")
    public String testCalendar(ModelMap model){
    	return VIEW+"testCalendar";
    }
    
    /**
     * 该订单的购买者信息可以让同行人看见
     * @param orderId
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/associateShow")
    public  @ResponseBody
    boolean associateShow(Long orderId,HttpServletRequest request,ModelMap model){
    	try {
    		Order order = orderService.find(orderId);
    		order.setIsAssociateShow(true);
    		orderService.update(order);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return true;
    }
    /**
     * 删除关闭的订单
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/deleteOrder", method = RequestMethod.GET)
    @ResponseBody
    public Message deleteOrder(Long orderId) {
    	Order order = orderService.find(orderId);
    	orderService.delete(order);
    	return SUCCESS_MESSAGE;
    }
}